package com.enba.boot.log.strategy;

import com.enba.boot.log.LogHelper;
import com.enba.boot.log.properties.LogProperties;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;

public class MongoStrategy implements LogHelper {

  @Autowired private MongoTemplate mongoTemplate;
  private final LogProperties logProperties;

  public MongoStrategy(LogProperties logProperties) {
    this.logProperties = logProperties;
  }

  @Override
  public void log(String message) {
    try (MongoClient mongoClient = MongoClients.create()) {
      MongoCollection<Document> collection =
          mongoTemplate.getDb().getCollection(logProperties.getTableName());
      Document doc = new Document("message", message);
      doc.append("timestamp", System.currentTimeMillis());
      collection.insertOne(doc);
    }
  }
}
